<?php


namespace catchAdmin\product\controller;


use catchAdmin\product\model\Product as ProductModel;
use catchAdmin\product\request\ProductCreateRequest;
use catchAdmin\product\request\ProductUpdateRequest;
use catcher\base\CatchController;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Utils;
use houniao\api\v1\Goods;
use think\facade\Db;

class Product extends CatchController
{
    protected $product;

    public function __construct(ProductModel $product)
    {
        $this->product = $product;
    }

    /**
     *
     * @throws \think\db\exception\DbException
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->product->getList($user['tenant_id']));
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getProduct(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->product->getAttrList($user['tenant_id']);
        return CatchResponse::success($list->toArray(), '查询成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function create(CatchAuth $auth, Request $request)
    {
        $params = $request->param();
        $user = $auth->user();
        $params['goods_Cname'] = $params['goods_name'];
        $params['tenant_id'] = $user['tenant_id'];
        $params['packing_id'] = implode(',', $params['packing_id']);
        $params['goods_id'] = date('YmdHis') . $user['tenant_id'];
        $params['barcode'] = date('YmdHis') . rand(1000, 9999);
        if ($this->product->where([
            'deleted_at' => 0, 'tenant_id' => $user['tenant_id'],
            'serial_number' => $params['serial_number']
        ])->find()) {
            return CatchResponse::fail('成品料号:' . $params['serial_number'] . '，已存在！');
        }
        if ($this->product->where([
            'deleted_at' => 0, 'tenant_id' => $user['tenant_id'],
            'sku' => $params['sku']
        ])->find()) {
            return CatchResponse::fail('型号:' . $params['sku'] . '，已存在！');
        }
        $this->product->storeBy($params);
        return CatchResponse::success('', '新建成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function update(Request $request)
    {
        $params = $request->filterEmptyField()->param();
        $params['packing_id'] = implode(',', $params['packing_id']);
        $id = $params['id'];
        if ($this->product->where([
            'deleted_at' => 0,
            'serial_number' => $params['serial_number'],

        ])->where('id', '<>', $id)->find()) {
            return CatchResponse::fail('成品料号:' . $params['serial_number'] . '，已存在！');
        }
        if ($this->product->where([
            'deleted_at' => 0,
            'sku' => $params['sku'],
        ])->where('id', '<>', $id)->find()) {
            return CatchResponse::fail('型号:' . $params['sku'] . '，已存在！');
        }
        $this->product->updateBy($id, $params);
        return CatchResponse::success('', '编辑成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $ids = Utils::stringToArrayBy($id);
        foreach ($ids as $_id) {
            $this->product->deleteBy($_id);
        }
        return CatchResponse::success('', '删除成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function goodsPacking(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->product->getGoodsPacking($user['tenant_id']);
        return CatchResponse::success($list->toArray(), '查询成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getGoods(CatchAuth $auth)
    {
        $user = $auth->user();
        $where = [];
        $where[] = ['deleted_at', '=', 0];
        if ($user['tenant_id'] != 0) {
            $where[] = ['tenant_id', '=', $user['tenant_id']];
        }
        $list = Db::table('db_product')->field('goods_id,goods_name,packing_id,serial_number,sku')->where($where)->select();
//        print_r(Db::table('db_product')->getLastSql());
        return CatchResponse::success($list, '查询成功');
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getPacking(CatchAuth $auth, Request $request)
    {
        $goods_name = $request->post('goods_name');
        $goods_id = $request->post('goods_id');
        $packing_id = Db::table('db_product')->where([
            'goods_name' => $goods_name,
            'goods_id' => $goods_id,
        ])->value('packing_id');
        if (empty($packing_id)) {
            return CatchResponse::fail('料号不存在！');
        }
        $packing_id = explode(',', $packing_id);
        $where = [];
        $where[] = ['packing_id', 'in', $packing_id];
        $list = Db::table('db_packing')->field('packing_id,unit_name,packing_num,layup_num')->where($where)->select()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['label'] = '1/' . $v['layup_num'] . '/' . $v['packing_num'] . '(托/箱/件)';
            //$list[$k]['label'] = '包装数量('.$v['packing_num'].')--包装单位('.$v['unit_name'].')--托盘可放置' . $v['layup_num']  . $v['unit_name'];
        }
        return CatchResponse::success($list, '查询成功');
    }

    public function detail($serial_number, CatchAuth $auth)
    {
        $user = $auth->user();

        $where = [];
        if ($user['tenant_id'] !== 0) {
            $where[] = ['tenant_id', '=', $user['tenant_id']];
        }
        $where[] = ['serial_number', '=', $serial_number];

        $field = ['*'];
        return CatchResponse::success($this->product->where($where)->field($field)->find(), '查询成功');
    }

    //商品库存
    public function inventory(CatchAuth $auth, Request $request)
    {
        $params = $request->filterEmptyField()->param();
        $where = [];

        $project_client = Db::table('db_warehouse_out')->where('warehouse_out_id', $params['warehouse_out_id'])->value('project_client');

        $where[] = ['project_client', '=', $project_client];
        $where[] = ['goods_id', '=', $params['goods_id']];
        $where[] = ['packing_id', '=', $params['packing_id']];

        $stock = DB::name('db_stock')
            ->field('SUM(Good_Qty) as Good_Qty,SUM(Hold_Qty) as Hold_Qty,SUM(NG_Qty) as NG_Qty')
            ->where($where)
            ->where('status', '<>', 1)
            ->where('deleted_at', 0)
            ->find();

        $stock_ids = Db::table('db_stock')->where($where)->column('stock_id');
        $map = [];
        $map[] = ['stock_id', 'in', $stock_ids];
        $map[] = ['deleted_at', '=', 0];
        $map[] = ['status', '=', 0];
        $map[] = ['stock_status', '=', 'Good'];
        $pick_good = Db::table('db_pick')->where($map)->sum('number');
        $map = [];
        $map[] = ['stock_id', 'in', $stock_ids];
        $map[] = ['deleted_at', '=', 0];
        $map[] = ['status', '=', 0];
        $map[] = ['stock_status', '=', 'Hold'];
        $pick_Hold = Db::table('db_pick')->where($map)->sum('number');
        $map = [];
        $map[] = ['stock_id', 'in', $stock_ids];
        $map[] = ['deleted_at', '=', 0];
        $map[] = ['status', '=', 0];
        $map[] = ['stock_status', '=', 'NG'];
        $pick_NG = Db::table('db_pick')->where($map)->sum('number');
        foreach ($stock as &$value) {
            $value = (int)$value;
        }
        $stock['Good_Qty'] -= $pick_good;
        $stock['Hold_Qty'] -= $pick_Hold;
        $stock['NG_Qty'] -= $pick_NG;
        return CatchResponse::success($stock, '');
    }
}